package config;

import com.alibaba.druid.pool.DruidDataSource;
import com.pxxy.toturial.entity.Computer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/******************
 * @Author yejf
 * @Description TODO
 */
@Configuration
@ComponentScan({"com.pxxy.toturial.dao.impl",
                "com.pxxy.toturial.service.impl",
                "com.pxxy.toturial.post"})
@Import(SpringTutorialConfig2.class)  //用来导入另一个注解配置类
@ImportResource(locations = {"classpath:applicationContext.xml"}) //用来加载xml配置文件的。
@PropertySource("classpath:db.properties")
//@EnableAspectJAutoProxy(proxyTargetClass = true)   //开启AOP
@EnableAspectJAutoProxy
@EnableTransactionManagement //开启申明式事务
public class SpringTutorialConfig {

    @Autowired
    private Environment env;

    @Bean  //此处不能使用 @Component, 因为Component只能修饰类型.
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        //设置 属性
        dataSource.setUrl(env.getProperty("url"));
        dataSource.setDriverClassName(env.getProperty("driver"));
        dataSource.setUsername(env.getProperty("user"));
        dataSource.setPassword(env.getProperty("password"));
        //
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(@Autowired DataSource dataSource) {
        //
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public PlatformTransactionManager transactionManager(@Autowired DataSource dataSource) {
        // 返回一个 DataSourceTransactionManager
        return new DataSourceTransactionManager(dataSource);
    }

}
